package cn.controller;

import cn.common.ExceResult;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.common.PageString;
import cn.filter.LoginCheck;
import cn.kpi.entity.sys.GeneralCodeEntity;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.workassessment.*;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.workassessment.IGRightsService;
import cn.kpi.service.workassessment.IGroupService;
import cn.kpi.service.workassessment.IWorkAssTemplateService;
import cn.kpi.service.workassessment.IWorkKPIService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.channels.FileLock;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.*;

@Controller
@RequestMapping("workass")
public class WorkAssessController extends BaseController {

    @Autowired
    private IWorkAssTemplateService iWorkAssTemplateService;

    @Autowired
    private IWorkKPIService iWorkKPIService;

    @Autowired
    private IGroupService iGroupService;

    @Autowired
    private IGRightsService iGRightsService;

    @Autowired
    private IOrgService orgService;

    //region 指标部分
    @RequestMapping(value = "/index_list")
    public String IndexList(Model model) {
        return "workassessment/work_index_list";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_index_list")
    public GridCommon<WorkAssTempCreateIndexEntity> GetIndexList(HttpServletRequest request) {
        List<WorkAssTempCreateIndexEntity> lst = null;
        GridCommon<WorkAssTempCreateIndexEntity> countlist = new GridCommon<WorkAssTempCreateIndexEntity>();
        try {

            String where = "";
            lst = iWorkAssTemplateService.GetIndexListByWhere(where);

            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");

        } catch (Exception e) {
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
        }
        return countlist;
    }


    @RequestMapping(value = "/index_edit")
    public String IndexEdit(Model model, Long assindexid) {
        try {
            String where = " AND assindextype=0";
            List<WorkAssTemplateIndexEntity> lst = iWorkAssTemplateService.GetTemplateIndexListByWhere(where);
            model.addAttribute("lst", lst);
            WorkAssTemplateIndexEntity entity = new WorkAssTemplateIndexEntity();
            if (assindexid > 0) {
                entity = iWorkAssTemplateService.GetIndexById(assindexid);
            }
            List<GeneralCodeEntity> items = new ArrayList<>();
            GeneralCodeEntity item = new GeneralCodeEntity();
            item.setCodedes("1");
            item.setCodename("属性");
            GeneralCodeEntity item1 = new GeneralCodeEntity();
            item1.setCodedes("2");
            item1.setCodename("值");
            items.add(item1);
            items.add(item);
            model.addAttribute("entity", entity);
            model.addAttribute("items", items);

        } catch (Exception ex) {

        }
        return "workassessment/work_index_edit";
    }

    @RequestMapping(value = "/add_templateindex")
    public String AddTemplateindex(HttpServletRequest request, HttpServletResponse response) {
        try {
            WorkAssTemplateIndexEntity entity = new WorkAssTemplateIndexEntity();
            if (request.getParameter("assindexid") == null || request.getParameter("assindexid").equals("")) {
                entity.setAssindexid(0L);
            } else {
                entity.setAssindexid(Long.parseLong(request.getParameter("assindexid")));
            }
            if (request.getParameter("datatype") != null && !request.getParameter("datatype").equals("")) {

                entity.setDatatype(Integer.parseInt(request.getParameter("datatype")));
            }
            entity.setDatavalue(request.getParameter("datavalue"));

            entity.setAssindextype(Integer.parseInt(request.getParameter("assindextype")));
            entity.setByuserid(this.GetLoginUserId());
            entity.setParentid(Long.valueOf(request.getParameter("parentid")));
//            entity.setScore(Integer.parseInt(request.getParameter("score")));
            entity.setTemplateid(Long.valueOf(0));
            if (entity.getAssindextype() == 1) {
                entity.setUassingredients(request.getParameter("uasscontent").trim());
                entity.setEvaluationstandard(request.getParameter("evaluationstandard").trim());
            } else {
                entity.setUasscontent(request.getParameter("uasscontent").trim());
            }

            int iResult = 0;
            if (entity.getAssindexid() > 0) {
                iResult = iWorkAssTemplateService.UpdateIndex(entity);
            } else {
                if (entity.getParentid() == 0) {
                    entity.setScore(0);
                }
                iResult = iWorkAssTemplateService.InsertTemplateIndexentity(entity);
            }


            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete_index")
    public ExceResult DeleteIndex(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long assindexid = Long.parseLong(request.getParameter("assindexid"));
            Long parentid = Long.parseLong(request.getParameter("parentid"));
            int iResult = iWorkAssTemplateService.DeleteIndex(assindexid, parentid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }
    //endregion

    //region 模板编辑
    @RequestMapping(value = "/work_template_list_alone_edit")
    public String TemplateListAloneEdit(Model model, Long templateid) {
        try {
            List<WorkAssTemplateIndexEntity> lst = iWorkAssTemplateService.GetTemplateIndexListRowSpanByTempId(templateid);
            model.addAttribute("lst", lst);
            model.addAttribute("templateid", templateid);

            String parentid = "";
            String usassid = "";
            for (int i = 0; i < lst.size(); i++) {
                WorkAssTemplateIndexEntity entity = lst.get(i);
                usassid += entity.getAssindexid().toString() + ",";
                if (parentid.length() > 0) {
                    String[] strarr = parentid.split(",");
                    String last = strarr[strarr.length - 1];
                    if (!last.equals(entity.getParentid().toString())) {
                        parentid += entity.getParentid().toString() + ",";
                    }
                } else {
                    parentid += entity.getParentid().toString() + ",";
                }

            }
            PageString pagestring = new PageString();
            pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
            pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
            model.addAttribute("pagestring", pagestring);

            if (templateid > 0) {
                WorkAssTemplateEntity ustempentity = iWorkAssTemplateService.GetWorkAssTemplateListById(templateid);
                model.addAttribute("ustempentity", ustempentity);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "workassessment/work_template_list_alone_edit";
    }


    @ResponseBody
    @RequestMapping(value = "/submit")
    public ExceResult submit(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));

            int iResult = iWorkAssTemplateService.UpdateStatus(templateid);
            result.setCode(200);
            result.setResult(iResult);
            result.setMsg("操作成功");
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @RequestMapping(value = "/create_templateindex")
    public String CreateTemplateIndex(HttpServletRequest request, HttpServletResponse response) {
        try {
            String strtemplateid = request.getParameter("templateid");
            Long templateid = Long.parseLong(strtemplateid);


            String parentids = request.getParameter("parentids");
            String assindexids = request.getParameter("assindexids");

            String[] parentidsArr = parentids.split(",");
            String[] assindexidsArr = assindexids.split(",");

            Long flag = 0L;
            List<WorkAssTempCreateIndexEntity> lst = new ArrayList<WorkAssTempCreateIndexEntity>();

            Long byuserid = this.GetLoginUserId();
            for (int i = 0; i < assindexidsArr.length; i++) {
                if (request.getParameter("cb_" + assindexidsArr[i]) != null) {
                    WorkAssTempCreateIndexEntity entity = new WorkAssTempCreateIndexEntity();
                    entity.setAssindexid(Long.parseLong(assindexidsArr[i]));
                    entity.setAssindextype(1);
                    entity.setParentid(Long.parseLong(request.getParameter("parentid_" + assindexidsArr[i])));
                    entity.setTemplateid(templateid);
                    entity.setEvaluationstandard(request.getParameter("evaluationstandard_" + assindexidsArr[i]));
//                    entity.setScore(Integer.parseInt(request.getParameter("score_" + assindexidsArr[i])));
                    entity.setUassingredients(request.getParameter("uassingredients_" + assindexidsArr[i]));
                    entity.setUasscontent(request.getParameter("uasscontent_" + entity.getParentid()));
                    entity.setByuserid(byuserid);
                    lst.add(entity);
                }
            }

            if (lst.size() <= 0) {
                return renderStringScript(response, "<script>window.parent.CloseDialog(0,'请选择指标项')</script>");
            }
            WorkAssTemplateEntity tempentity = new WorkAssTemplateEntity();

            tempentity.setTemplatename(request.getParameter("templatename"));
            tempentity.setBegintime(Date.valueOf(request.getParameter("begintime")));
            tempentity.setEndtime(Date.valueOf(request.getParameter("endtime")));
            tempentity.setTemplatedes(request.getParameter("templatedes"));
            tempentity.setByuserid(byuserid);
            int iResult = 0;
            if (templateid > 0) {
                tempentity.setTemplateid(templateid);
                iResult = iWorkAssTemplateService.UpdateWorkAssTempEntity(lst, tempentity);
            } else {
                iResult = iWorkAssTemplateService.CreateTemplateAndIndex(lst, tempentity);
            }
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    @RequestMapping(value = "/work_template_list_alone")
    public String TemplateListAlone(Model model) {
        return "workassessment/work_template_list_alone";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<WorkAssTemplateEntity> GetList(HttpServletRequest request) {

        List<WorkAssTemplateEntity> lst = null;
        LayTable<WorkAssTemplateEntity> layTable = new LayTable<WorkAssTemplateEntity>();
        try {
            String templatename = request.getParameter("templatename");

            String where = "";
            if (templatename != null && templatename.length() > 0) {
                where += " AND templatename LIKE '%" + templatename.trim() + "%'";
            }

            lst = iWorkAssTemplateService.GetWorkAssTemplateListByWhere(where);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iWorkAssTemplateService.GetWorkAssTemplateListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/delete_template")
    public ExceResult DeleteTemplate(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));
            int iResult = iWorkAssTemplateService.DeleteWorkTempEntity(templateid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @RequestMapping(value = "/work_templae_list_org_edit")
    public String templateOrgEdit(Model model, Long templateid) {
        try {
            List<WorkAssTemplateOrgEntity> lst = iWorkAssTemplateService.GetTempOrgListByTempId(templateid);
            model.addAttribute("lst", lst);
            model.addAttribute("templateid", templateid);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "workassessment/work_templae_list_org_edit";
    }

    @ResponseBody
    @RequestMapping(value = "/create_templateorg")
    public ExceResult CreateTemplateOrg(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String orgid = request.getParameter("origid");
            Long templateidl = Long.parseLong(request.getParameter("templateid"));

            String[] oridArr = orgid.split(",");

            Long byuserid = this.GetLoginUserId();//未使用

            List<Long> orgList = new ArrayList<>();
            for (String s : oridArr) {
                orgList.add(Long.valueOf(s));
            }
            int iResult = iWorkAssTemplateService.InsertWorkTempOrgBatch(templateidl, orgList);

            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    //endregion

    //region 机构分组
    @RequestMapping(value = "/group_list")
    public String GroupList(Model model) {
        return "workassessment/group_list";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_group_list")
    public LayTable<GroupEntity> GetGroupList(HttpServletRequest request) {

        GridCommon<GroupEntity> countlist = new GridCommon<GroupEntity>();
        List<GroupEntity> lst = null;
        LayTable<GroupEntity> layTable = new LayTable<GroupEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String GroupName = request.getParameter("groupname");
            System.out.println(GroupName);
            String where = "1=1 ";
            if (GroupName != null && GroupName.length() > 0) {
                where += " AND groupname like '%" + GroupName + "%'";
            }

            int beginrow = (page - 1) * limit;
            int endrow = limit;
            String order = " orderindex ";
            lst = iGroupService.GetGroupListLimit(where, order, beginrow, endrow);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");

            layTable.setCode(0);
            layTable.setCount(iGroupService.GetGroupListCount(where));
            layTable.setData(lst);

        } catch (Exception e) {
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
        }
        return layTable;
    }

    @RequestMapping(value = "/add_group")
    public String AddGroup(HttpServletRequest request, HttpServletResponse response) {
        try {
            GroupEntity entity = new GroupEntity();
            entity.setGroupid(Long.parseLong(request.getParameter("groupid")));
            entity.setRemark(request.getParameter("remark"));
            entity.setGroupname(request.getParameter("groupname"));
            entity.setOrderindex(Integer.parseInt(request.getParameter("orderindex")));


            int iResult = 0;
            if (entity.getGroupid() > 0) {
                iResult = iGroupService.UpdateEntity(entity);
                ;
            } else {
                iResult = iGroupService.InsertEntity(entity);
            }

            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete_group")
    public ExceResult DeleteGroup(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long groupid = Long.parseLong(request.getParameter("groupid"));
            int iResult = iGroupService.DeleteEntity(groupid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @RequestMapping(value = "/work_rights")
    public String GroupRights(Model model, Long groupid) {
        model.addAttribute("groupid", groupid);
        return "workassessment/org_group_edit";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_list")
    public List<GroupOrgEntity> GetOrgList(HttpServletRequest request) {
        List<GroupOrgEntity> lst = null;
        try {
            Long groupid = Long.parseLong(request.getParameter("groupid"));

            lst = iGRightsService.GetGroupOrgList(groupid);
            for (int i = 0; i < lst.size(); i++) {
                if (lst.get(i).getIschecked() == 1) {
                    lst.get(i).setLay_CHECKED(true);
                } else {
                    lst.get(i).setLay_CHECKED(false);
                }
            }

            return lst;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lst;
    }

    @ResponseBody
    @RequestMapping(value = "/insert_grouporg")
    public ExceResult InsertGroupOrg(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long groupid = Long.parseLong(request.getParameter("groupid"));
            String strorgids = request.getParameter("orgids");
            String[] orgidArr = strorgids.split(",");

            List<Long> list = new ArrayList<Long>();
            for (int i = 0; i < orgidArr.length; i++) {
                list.add(Long.parseLong(orgidArr[i]));
            }

            int iResult = iGRightsService.InsertGroupOrg(list, groupid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }
    //endregion

    //region 指标打分部分
    @RequestMapping(value = "/work_kp_list")
    public String kpiListView(Model model) {
        return "workassessment/work_kp_list";
    }

    //模板
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_kpi_list")
    public LayTable<WorkAssTemplateEntity> GetkpiList(HttpServletRequest request) {

        List<WorkAssTemplateEntity> lst = null;
        LayTable<WorkAssTemplateEntity> layTable = new LayTable<WorkAssTemplateEntity>();
        try {
            String templatename = request.getParameter("templatename");

            String where = "";
            if (templatename != null && templatename.length() > 0) {
                where += " AND templatename LIKE '%" + templatename.trim() + "%'";
            }

            lst = iWorkAssTemplateService.GetWorkAssTemplateListByWhere(where);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iWorkAssTemplateService.GetWorkAssTemplateListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @RequestMapping(value = "/work_kp_read")
    public String kpiread(Model model, Long templateid) {
        try {
            List<WorkAssTempCreateIndexEntity> lstdetail = iWorkAssTemplateService.GetTemplateIndexBytemplateid(templateid);

            Map<String, String> columMap = new HashMap();
            String columns = "";

            for (int i = 0; i < lstdetail.size(); i++) {
                String key = lstdetail.get(i).getUasscontent();
                if (columMap.containsKey(key)) {
                    Integer newValue = Integer.valueOf(columMap.get(key)) + 1;
                    columMap.put(key, String.valueOf(newValue));
                } else {
                    columMap.put(key, "1");
                }

                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
            }
            columns = columns.substring(0, columns.length() - 1);

            List<Map> lstorg = iWorkKPIService.GetWorkKPIMapByTempIdAndColumns(templateid, columns);

            System.out.println(JSON.toJSONString(lstorg));

            model.addAttribute("columt", columMap);
            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", lstorg);


        } catch (Exception e) {

        }
        return "workassessment/work_kp_read";
    }

    @RequestMapping(value = "/work_kp_look")
    public String kpilook(Model model, Long templateid) {


        return "workassessment/work_kp_look";


    }

    @RequestMapping(value = "/work_kp_exportword")
    public String kpiexpWord2(Model model, HttpServletRequest request) {
        String tempidstr = request.getParameter("templateid");
        Long templateid = 20l;
        if (tempidstr != null) templateid = Long.valueOf(tempidstr);
        try {
            List<WorkAssTempCreateIndexEntity> lstdetail = iWorkAssTemplateService.GetTemplateIndexBytemplateid(templateid);

            Map<String, String> columMap = new HashMap();
            List<TitleEntity> titleEntities = new ArrayList<>();
            String columns = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                String key = lstdetail.get(i).getUasscontent();
                if (columMap.containsKey(key)) {
                    Integer newValue = Integer.valueOf(columMap.get(key)) + 1;

//                    titleEntities.remove(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), columMap.get(key)));
                    titleEntities.add(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), newValue.toString()));

                    columMap.put(key, String.valueOf(newValue));

                } else {
                    titleEntities.add(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), "1"));

                    columMap.put(key, "1");
                }

                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
            }


            columns = columns.substring(0, columns.length() - 1);
            List<Map> AssindexS = iWorkAssTemplateService.getAssindexS(templateid);


            //实际数据
            List<Map> lstorg = iWorkKPIService.GetWorkKPIMapByTempIdAndColumns(templateid, columns);
            //应该有的岗位数据
            List<WorkAssGroupOrgEntity> buAssTemplateOrgEntities = iWorkAssTemplateService.GetGroupOrgListByTempId(templateid);
            List<Map> newMaps = new ArrayList<>();


            List<WorkKPItemEntity> weightsList = iWorkKPIService.getWeight(templateid);
            for (int i = 0; i < weightsList.size(); i++) {


                for (int j = 0; j < lstdetail.size(); j++) {

                    if (weightsList.get(i).getAssindexid() == lstdetail.get(j).getAssindexid()) {
                        if (weightsList.get(i).getKpiweight() != null)

                            lstdetail.get(j).setKpiweight(new BigDecimal(weightsList.get(i).getKpiweight().toString()));

                    }

                }


            }


            //数据合并
            for (WorkAssGroupOrgEntity buAssTemplateOrgEntity : buAssTemplateOrgEntities) {
                boolean isContent = false;
                long orgid = buAssTemplateOrgEntity.getOrgid();
                long groupid = 0;

                if (buAssTemplateOrgEntity.getGroupid() != null) {
                    groupid = buAssTemplateOrgEntity.getGroupid();//todo:未分组的需要格外考虑
                }

                long rowspan = 0;
                String groupname = "";
                if (buAssTemplateOrgEntity.getGroupname() != null) {
                    rowspan = buAssTemplateOrgEntity.getRowspan();
                    groupname = buAssTemplateOrgEntity.getGroupname();
                } else {

                }

                for (Map map : lstorg) {//是否已经有值
                    if (map.get("orgid") == orgid) {
                        isContent = true;
                        newMaps.add(map);
                    }
                }
                if (!isContent) {//初始化数据
                    Map mape = new HashMap();

                    mape.put("groupid", groupid);
                    mape.put("groupname", groupname);
                    mape.put("rowspan", rowspan);
                    mape.put("orgid", orgid);
                    mape.put("orgname", buAssTemplateOrgEntity.getOrgname());
                    mape.put("templateid", templateid);
                    for (WorkAssTempCreateIndexEntity indexEntity : lstdetail) {
                        mape.put(indexEntity.getAssindexidcolum(), "");
                    }
                    newMaps.add(mape);
                }
            }
//            lstorg.addAll(newMaps);

            System.out.println(JSON.toJSONString(lstorg));


            List<TitleEntity> newList = new ArrayList<>();

            Map<String, String> newMap = new HashMap();
            for (int i = titleEntities.size() - 1; i >= 0; i--) {

                if (newMap.containsKey(titleEntities.get(i).getId())) {
                } else {
                    newMap.put(titleEntities.get(i).getId().toString(), "1");
                    newList.add(titleEntities.get(i));

                }


            }

            for (int i = 0; i < newList.size(); i++) {
//                权重总数
                BigDecimal sum = new BigDecimal("0");

                for (int j = 0; j < lstdetail.size(); j++) {

                    if (Integer.parseInt(newList.get(i).getId()) == lstdetail.get(j).getParentid()) {
                        if (lstdetail.get(j).getKpiweight() != null && lstdetail.get(j).getKpiweight().toString().trim() != "")

                            sum = lstdetail.get(j).getKpiweight().add(sum);
                    }


                }
                newList.get(i).setSum(sum);


            }

            List<TitleEntity> titleEntities1 = new ArrayList<>();
            for (int i = newList.size() - 1; i >= 0; i--) { //解决倒叙问题
                titleEntities1.add(newList.get(i));

            }
            model.addAttribute("columt", titleEntities1);
            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", newMaps);
            model.addAttribute("templateid", templateid);
            model.addAttribute("read", 1);//只读

        } catch (Exception e) {

            String mess = e.getMessage();

        }
        return "workassessment/work_kp_exportword";
    }

    @ResponseBody
    @RequestMapping(value = "/gettemplatebybegin")
    public LayTable<WorkAssTemplateEntity> getTemp(HttpServletRequest request, HttpServletResponse response) {
        LayTable<WorkAssTemplateEntity> layTable = new LayTable<WorkAssTemplateEntity>();
        try {
            String strWhere = request.getParameter("strWhere");

            String[] list = strWhere.split(",");
            int year = Integer.parseInt(list[0]);
            int quarter = Integer.parseInt(list[1]);

            List<WorkAssTemplateEntity> lstdetail = iWorkAssTemplateService.getWorkAssTemplateEntitys(year, quarter);
            layTable.setData(lstdetail);
        } catch (Exception ex) {

        }
        return layTable;


    }

    @ResponseBody
    @RequestMapping(value = "/add_title")
    public String addTitle(HttpServletRequest request, HttpServletResponse response) {
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));
            String titleName = request.getParameter("titlename");
            iWorkAssTemplateService.updateTitlleName(templateid, titleName);

            return "1";

        } catch (Exception ex) {

        }
        return "";


    }

    @ResponseBody
    @RequestMapping(value = "/get_title")
    public String getTitle(HttpServletRequest request, HttpServletResponse response) {
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));


            List<WorkAssTemplateEntity> lstdetail = iWorkAssTemplateService.GetWorkAssTemplateListByWhere(" and templateid=" + templateid);

            if (lstdetail.size() > 0) return lstdetail.get(0).getTitleName();

        } catch (Exception ex) {

        }
        return "";


    }

    @RequestMapping(value = "/export1")
    public String kpiedit1(Model model) {

        return "workassessment/export2";


    }


    @RequestMapping(value = "/work_kp_edit")
    public String kpiedit(Model model, int read, Long templateid) {
        try {
            List<WorkAssTempCreateIndexEntity> lstdetail = iWorkAssTemplateService.GetTemplateIndexBytemplateid(templateid);

            Map<String, String> columMap = new HashMap();
            List<TitleEntity> titleEntities = new ArrayList<>();
            String columns = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                String key = lstdetail.get(i).getUasscontent();
                if (columMap.containsKey(key)) {
                    Integer newValue = Integer.valueOf(columMap.get(key)) + 1;

                    titleEntities.add(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), newValue.toString()));

                    columMap.put(key, String.valueOf(newValue));

                } else {
                    titleEntities.add(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), "1"));

                    columMap.put(key, "1");
                }

                columns += "sum(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
//                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN orgscore ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "_org',";


            }
            columns = columns.substring(0, columns.length() - 1);
            List<Map> AssindexS = iWorkAssTemplateService.getAssindexS(templateid);
            //实际数据
            List<Map> lstorg = iWorkKPIService.GetWorkKPIMapByTempIdAndColumns(templateid, columns);
            //应该有的岗位数据
            List<WorkAssGroupOrgEntity> buAssTemplateOrgEntities = iWorkAssTemplateService.GetGroupOrgListByTempId(templateid);
            List<Map> newMaps = new ArrayList<>();
            List<WorkKPItemEntity> weightsList = iWorkKPIService.getWeight(templateid);
            for (int i = 0; i < weightsList.size(); i++) {
                for (int j = 0; j < lstdetail.size(); j++) {
                    if (weightsList.get(i).getAssindexid() == lstdetail.get(j).getAssindexid()) {
                        if (weightsList.get(i).getKpiweight() != null)

                            lstdetail.get(j).setKpiweight(new BigDecimal(weightsList.get(i).getKpiweight().toString()));

                    }
                }
            }
            //数据合并
            for (WorkAssGroupOrgEntity buAssTemplateOrgEntity : buAssTemplateOrgEntities) {
                boolean isContent = false;
                long orgid = buAssTemplateOrgEntity.getOrgid();
                long groupid = 0;
                if (buAssTemplateOrgEntity.getGroupid() != null) {
                    groupid = buAssTemplateOrgEntity.getGroupid();//todo:未分组的需要格外考虑
                }
                long rowspan = 0;
                String groupname = "";
                if (buAssTemplateOrgEntity.getGroupname() != null) {
                    rowspan = buAssTemplateOrgEntity.getRowspan();
                    groupname = buAssTemplateOrgEntity.getGroupname();
                } else {
                }
                for (Map map : lstorg) {//是否已经有值
                    if (map.get("orgid") == orgid) {
                        isContent = true;
                        newMaps.add(map);
                    }
                }
                if (!isContent) {//初始化数据
                    Map mape = new HashMap();
                    mape.put("groupid", groupid);
                    mape.put("groupname", groupname);
                    mape.put("rowspan", rowspan);
                    mape.put("orgid", orgid);
                    mape.put("orgname", buAssTemplateOrgEntity.getOrgname());
                    mape.put("templateid", templateid);
                    for (WorkAssTempCreateIndexEntity indexEntity : lstdetail) {
                        mape.put(indexEntity.getAssindexidcolum(), "");
                    }
                    newMaps.add(mape);
                }
            }
//            lstorg.addAll(newMaps);

            System.out.println(JSON.toJSONString(lstorg));
            List<TitleEntity> newList = new ArrayList<>();
            Map<String, String> newMap = new HashMap();
            for (int i = titleEntities.size() - 1; i >= 0; i--) {
                if (newMap.containsKey(titleEntities.get(i).getId())) {
                } else {
                    newMap.put(titleEntities.get(i).getId().toString(), "1");
                    newList.add(titleEntities.get(i));
                }
            }
            for (int i = 0; i < newList.size(); i++) {
//                权重总数
                BigDecimal sum = new BigDecimal("0");
                for (int j = 0; j < lstdetail.size(); j++) {
                    if (Integer.parseInt(newList.get(i).getId()) == lstdetail.get(j).getParentid()) {
                        if (lstdetail.get(j).getKpiweight() != null && lstdetail.get(j).getKpiweight().toString().trim() != "")
                            sum = lstdetail.get(j).getKpiweight().add(sum);
                    }

                }
                newList.get(i).setSum(sum);
            }
            List<TitleEntity> titleEntities1 = new ArrayList<>();
            for (int i = newList.size() - 1; i >= 0; i--) { //解决倒叙问题
                titleEntities1.add(newList.get(i));
            }
            List<Map> sumScore = iWorkAssTemplateService.getSumScore(templateid);
            float Allsumscore = 0;
            for (int i = 0; i < lstdetail.size(); i++) {
                for (int j = 0; j < sumScore.size(); j++) {

                    if (lstdetail.get(i).getAssindexid() == Long.parseLong(sumScore.get(j).get("assindexid").toString())) {

                        if (sumScore.get(j).get("sumscore") != null && sumScore.get(j).get("sumscore") != "") {
                            BigDecimal sumscore = new BigDecimal(sumScore.get(j).get("sumscore").toString());
                            lstdetail.get(i).setSumscore(sumscore);
                            if (lstdetail.get(i).getDatatype() == 2)
                                Allsumscore += Float.parseFloat(sumScore.get(j).get("sumscore").toString());
                        }
                    }
                }
            }
            model.addAttribute("sumscore", new BigDecimal(Allsumscore));
            model.addAttribute("columt", titleEntities1);
            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", newMaps);


            model.addAttribute("templateid", templateid);
            model.addAttribute("read", read);

        } catch (Exception e) {

            String mess = e.getMessage();

        }
        return "workassessment/work_kp_edit";
    }


    @RequestMapping(value = "/export")
    public String export(Model model, Long templateid) {


        try {
            List<WorkAssTempCreateIndexEntity> lstdetail = iWorkAssTemplateService.GetTemplateIndexBytemplateid(templateid);

            Map<String, String> columMap = new HashMap();
            List<TitleEntity> titleEntities = new ArrayList<>();
            String columns = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                String key = lstdetail.get(i).getUasscontent();
                if (columMap.containsKey(key)) {
                    Integer newValue = Integer.valueOf(columMap.get(key)) + 1;

//                    titleEntities.remove(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), columMap.get(key)));
                    titleEntities.add(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), newValue.toString()));

                    columMap.put(key, String.valueOf(newValue));

                } else {
                    titleEntities.add(new TitleEntity(key, lstdetail.get(i).getParentid().toString(), "1"));

                    columMap.put(key, "1");
                }

                columns += "sum(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
            }


            columns = columns.substring(0, columns.length() - 1);
            List<Map> AssindexS = iWorkAssTemplateService.getAssindexS(templateid);


            //实际数据
            List<Map> lstorg = iWorkKPIService.GetWorkKPIMapByTempIdAndColumns(templateid, columns);
            //应该有的岗位数据
            List<WorkAssGroupOrgEntity> buAssTemplateOrgEntities = iWorkAssTemplateService.GetGroupOrgListByTempId(templateid);
            List<Map> newMaps = new ArrayList<>();


            List<WorkKPItemEntity> weightsList = iWorkKPIService.getWeight(templateid);
            for (int i = 0; i < weightsList.size(); i++) {
                for (int j = 0; j < lstdetail.size(); j++) {
                    if (weightsList.get(i).getAssindexid() == lstdetail.get(j).getAssindexid()) {
                        if (weightsList.get(i).getKpiweight() != null)
                            lstdetail.get(j).setKpiweight(new BigDecimal(weightsList.get(i).getKpiweight().toString()));
                    }
                }
            }
            //数据合并
            for (WorkAssGroupOrgEntity buAssTemplateOrgEntity : buAssTemplateOrgEntities) {
                boolean isContent = false;
                long orgid = buAssTemplateOrgEntity.getOrgid();
                long groupid = 0;

                if (buAssTemplateOrgEntity.getGroupid() != null) {
                    groupid = buAssTemplateOrgEntity.getGroupid();//todo:未分组的需要格外考虑
                }

                long rowspan = 0;
                String groupname = "";
                if (buAssTemplateOrgEntity.getGroupname() != null) {
                    rowspan = buAssTemplateOrgEntity.getRowspan();
                    groupname = buAssTemplateOrgEntity.getGroupname();
                } else {

                }

                for (Map map : lstorg) {//是否已经有值
                    if (map.get("orgid") == orgid) {
                        isContent = true;
                        newMaps.add(map);
                    }
                }
                if (!isContent) {//初始化数据
                    Map mape = new HashMap();

                    mape.put("groupid", groupid);
                    mape.put("groupname", groupname);
                    mape.put("rowspan", rowspan);
                    mape.put("orgid", orgid);
                    mape.put("orgname", buAssTemplateOrgEntity.getOrgname());
                    mape.put("templateid", templateid);
                    for (WorkAssTempCreateIndexEntity indexEntity : lstdetail) {
                        mape.put(indexEntity.getAssindexidcolum(), "");
                    }
                    newMaps.add(mape);
                }
            }
//            lstorg.addAll(newMaps);

            System.out.println(JSON.toJSONString(lstorg));


            List<TitleEntity> newList = new ArrayList<>();

            Map<String, String> newMap = new HashMap();
            for (int i = titleEntities.size() - 1; i >= 0; i--) {

                if (newMap.containsKey(titleEntities.get(i).getId())) {
                } else {
                    newMap.put(titleEntities.get(i).getId().toString(), "1");
                    newList.add(titleEntities.get(i));

                }


            }

            for (int i = 0; i < newList.size(); i++) {
//                权重总数
                BigDecimal sum = new BigDecimal("0");

                for (int j = 0; j < lstdetail.size(); j++) {

                    if (Integer.parseInt(newList.get(i).getId()) == lstdetail.get(j).getParentid()) {
                        if (lstdetail.get(j).getKpiweight() != null && lstdetail.get(j).getKpiweight().toString().trim() != "")

                            sum = lstdetail.get(j).getKpiweight().add(sum);
                    }
                }
                newList.get(i).setSum(sum);


            }

            List<TitleEntity> titleEntities1 = new ArrayList<>();
            for (int i = newList.size() - 1; i >= 0; i--) { //解决倒叙问题
                titleEntities1.add(newList.get(i));

            }
            model.addAttribute("columt", titleEntities1);
            model.addAttribute("titleh", lstdetail);

            for (int i = 0; i < lstdetail.size(); i++) {
                //全局
                float score = 0;
                for (int j = 0; j < newMaps.size(); j++) {
                    Object ss = newMaps.get(j).get(lstdetail.get(i).getAssindexid().toString());
                    if (ss == null) {

                    } else {
                        score += Float.parseFloat(ss.toString());
                    }

                }
                lstdetail.get(i).setSumscore(new BigDecimal(score));
            }


            for (int j = 0; j < newMaps.size(); j++) {
                //总计
                float score = 0;
                for (int i = 0; i < lstdetail.size(); i++) {
                    if (newMaps.get(j).get(lstdetail.get(i).getAssindexid().toString()) != null) {

                        if (lstdetail.get(i).getKpiweight() != null) {



                            newMaps.get(j).put("sumscore", lstdetail.get(i).getKpiweight().floatValue());

                        }
                    }


                }
            }

            HashMap<String, String> groupHs = new HashMap<>();
            for (int i = 0; i < newMaps.size(); i++) {

                String groupid = newMaps.get(i).get("groupid").toString();
                if (!groupHs.containsKey(groupid)) {
                    groupHs.put(groupid, "");
                }
            }

            for (String key : groupHs.keySet()) {

                HashMap<String, String> hs = new HashMap<>();
                for (int i = 0; i < newMaps.size(); i++) {

                    if (newMaps.get(i).get("groupid").toString().equals(key)) {

                        if (!hs.containsKey(newMaps.get(i).get("sumscore"))) {

                            hs.put(newMaps.get(i).get("sumscore").toString(), "");
                        }
                    }
                }
                float[] descArray = new float[hs.size()];
                int index = 0;
                for (String score : hs.keySet()) {
                    descArray[index] = Float.parseFloat(score);
                    index++;
                }
                Arrays.sort(descArray);
                int orderIndex = 0;
                for (int i = descArray.length - 1; i >= 0; i--) {
                    orderIndex++;
                    for (int j = 0; j < newMaps.size(); j++) {
                        if (newMaps.get(j).get("groupid").toString().equals(key) && descArray[i] == Float.parseFloat(newMaps.get(j).get("sumscore").toString())) {
                            newMaps.get(j).put("orderindex", orderIndex);
                        }
                    }
                }
            }
            List<WorkAssTemplateEntity> titles = iWorkAssTemplateService.GetWorkAssTemplateListByWhere(" and templateid=" + templateid);
            String title = "";
            if (titles.size() > 0) title = titles.get(0).getTitleName();

            List<Map> sumScore = iWorkAssTemplateService.getSumScore(templateid);
            float Allsumscore = 0;
            for (int i = 0; i < lstdetail.size(); i++) {
                for (int j = 0; j < sumScore.size(); j++) {

                    if (lstdetail.get(i).getAssindexid() == Long.parseLong(sumScore.get(j).get("assindexid").toString())) {

                        if (sumScore.get(j).get("sumscore") != null && sumScore.get(j).get("sumscore") != "") {
                            BigDecimal sumscore = new BigDecimal(sumScore.get(j).get("sumscore").toString());
                            lstdetail.get(i).setSumscore(sumscore);
                            if (lstdetail.get(i).getDatatype() == 2)
                                Allsumscore += Float.parseFloat(sumScore.get(j).get("sumscore").toString());
                        }
                    }
                }
            }
            model.addAttribute("sumscore", new BigDecimal(Allsumscore));
            model.addAttribute("databody", newMaps);
            model.addAttribute("templateid", templateid);
            model.addAttribute("read", "1");
            model.addAttribute("title", title);

        } catch (Exception e) {
            String mess = e.getMessage();
        }
        return "workassessment/work_kp_export";
    }


    @ResponseBody
    @RequestMapping(value = "/get_CheckorgList")
    public List<WorkAssTemplateOrgEntity> getCheckOrgList(HttpServletRequest request, HttpServletResponse response) {
        List<WorkAssTemplateOrgEntity> lst = new ArrayList<>();
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));
            lst = iWorkAssTemplateService.GetTempOrgListByTempId(templateid);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return lst;
    }


    @ResponseBody
    @RequestMapping(value = "/get_orgList")
    public GridCommon<OrgEntity> getOrgList(HttpServletRequest request, HttpServletResponse response) {
        List<OrgEntity> list = new ArrayList<>();
        GridCommon<OrgEntity> rs = new GridCommon<>();
        try {
            list = orgService.GetOrgListByWhere("  and orgtype=0  ");
            rs.setCountRecord(list.size());
            rs.setItems(list);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return rs;
    }

    @RequestMapping(value = "/create_kpiscore")
    public String CreateKpiScore(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<WorkKPItemEntity> bukpItemEntities = new ArrayList<>();
            //获取所有的值
            Map<String, String> map = new HashMap<>();
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                String value = request.getParameter(name);
                map.put(name, value);
            }
            Long templateId = Long.valueOf(map.get("templateid"));
            for (String key : map.keySet()) {
                if (!key.equals("templateid")) {
                    String[] indexs = key.split("_");
                    if (indexs.length == 3) {
                        WorkKPItemEntity bukpItemEntity = new WorkKPItemEntity();
                        bukpItemEntity.setTemplateid(templateId);
                        bukpItemEntity.setOrgid(Long.valueOf(indexs[1]));
                        bukpItemEntity.setAssindexid(Long.valueOf(indexs[2]));
                        if (map.get(key) != "") {
                            bukpItemEntity.setScore(map.get(key));
                        }
                        String orgKey = "orgscore_" + indexs[1] + "_" + bukpItemEntity.getAssindexid();
                        if (map.get(orgKey) != null && map.get(orgKey) != "") {
                            BigDecimal orgScore = new BigDecimal(map.get(orgKey));
                            bukpItemEntity.setOrgscore(orgScore);
                        }
                        String sunkey = "sum_" + bukpItemEntity.getAssindexid();
                        if (map.get(sunkey) != null && map.get(sunkey) != "") {
                            BigDecimal sumScore = new BigDecimal(map.get(sunkey));
                            bukpItemEntity.setSumscore(sumScore);
                        }
                        String weightKey = "weight_" + bukpItemEntity.getAssindexid();
                        if (map.get(weightKey) != null && map.get(weightKey) != "") {
                            BigDecimal wegiht = new BigDecimal(map.get(weightKey));
                            bukpItemEntity.setKpiweight(wegiht);
                        }
                        List<Map> maps = iWorkAssTemplateService.getAssindexS(bukpItemEntity.getAssindexid());
                        if (maps.size() > 0)
                            bukpItemEntity.setParentid(Integer.parseInt(maps.get(0).get("parentid").toString()));
                        bukpItemEntities.add(bukpItemEntity);
                    }
                }
            }
            int iResult = iWorkKPIService.InsertWorkKPItemBatch(templateId, bukpItemEntities);
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    //endregion

}
